package znbkCNtxl.CNTXL_GCT;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.BaseFragment;
import com.example.znbk.znbklibrary.util.LancooUtils;
import com.lancoo.znbkxx.R;
import com.xujiaji.happybubble.BubbleDialog;
import com.xujiaji.happybubble.BubbleLayout;
import com.xujiaji.happybubble.Util;

import java.util.List;

import znbkCNtxl.GetNtxlJson.CNtxlPaperEntity;

@SuppressLint("ValidFragment")
public class CNtxlGctFragment extends BaseFragment {

    private int fromModel = -1;
    private List<CNtxlPaperEntity> CNtxlPaperEntity;
    private int childIndex = -1;
    private CallBackFragmentGct callBackFragmentGct;
    public CNtxlGctFragment(int fromModel,List<CNtxlPaperEntity> CNtxlPaperEntity, final int childIndex, CallBackFragmentGct callBackFragmentGct){
        this.fromModel = fromModel;
        this.CNtxlPaperEntity = CNtxlPaperEntity;
        this.childIndex = childIndex;
        this.callBackFragmentGct = callBackFragmentGct;
    }

    @Override
    protected int createLayout() {
        return R.layout.cntxl_fragment_gct;
    }


    private boolean isFristTime = true;
    /** 标签之间的间距 px */
    final int itemMargins = 12;
    /** 标签的行间距 px */
    final int lineMargins = 60;
    private ScrollView mSvGct;
    private LinearLayout mLlContainer;
    //    private String text1 = "A group of scientists were ? planning to go to the countryside to do a scientific research in order to find out that whether the environment of the country had polluted . On arrival , they started to check the air and water . To our surprise , they found how terribly the situation was . They could see the serious pollution . Looking into the cause , they persuade the government to pass the law to protect the environment and kept the balance of nature . Now everything has changed . Birds are singing while trees and grass are waving .";
//    private String[] tags = text1.split(" ");
    private String[] tags;

    private LinearLayout mLlGctAnswer;
    private LinearLayout mLlAnswer;
    private Button mBtnSubmit;

    @Override
    protected void initView(View view) {

        String QuesBody = CNtxlPaperEntity.get(childIndex).getQuesFromTK().getQuesBody();
        tags = QuesBody.split(" ");

        mSvGct = view.findViewById(R.id.sv_gct);
        mSvGct.setOverScrollMode(android.view.View.OVER_SCROLL_NEVER);
        mLlContainer =  view.findViewById(R.id.ll_container);
        mLlGctAnswer = view.findViewById(R.id.ll_gctAnswer);
        mLlAnswer =  view.findViewById(R.id.ll_answer);
        int AnswerSize = CNtxlPaperEntity.get(childIndex).getFavouriteAndNote().getChildList().get(0).
                getSubChildList().get(0).getSubChildItem().size();
        TextView[] mTvAnswer = new TextView[AnswerSize];
        for(int i=0;i<AnswerSize;i++){
            mTvAnswer[i] = new TextView(getActivity());
            int SortIndex = CNtxlPaperEntity.get(childIndex).getQuesFromTK().getChildList().get(0).
                    getSubChildList().get(0).getSubChildItem().get(i).getSortIndex();
            String StuAnswer = CNtxlPaperEntity.get(childIndex).getFavouriteAndNote().getChildList().get(0).
                    getSubChildList().get(0).getSubChildItem().get(i).getStuAnswer();
            String ItemAnswer = CNtxlPaperEntity.get(childIndex).getFavouriteAndNote().getChildList().get(0).
                    getSubChildList().get(0).getSubChildItem().get(i).getItemAnswer();
            if(ItemAnswer.equals(StuAnswer)){
                mTvAnswer[i].setTextColor(Color.parseColor("#00b30d"));
            }else{
                mTvAnswer[i].setTextColor(Color.parseColor("#ff0000"));
            }
            mTvAnswer[i].setText(SortIndex+"."+ItemAnswer);
            mLlAnswer.addView(mTvAnswer[i]);
        }

        mBtnSubmit = view.findViewById(R.id.btn_submit);
        int SubmitState = CNtxlPaperEntity.get(childIndex).getFavouriteAndNote().getSubmitState();
        if(SubmitState!=2) {
            mLlGctAnswer.setVisibility(View.GONE);
            mBtnSubmit.setVisibility(View.VISIBLE);
        }else{
            mLlGctAnswer.setVisibility(View.VISIBLE);
            mBtnSubmit.setVisibility(View.GONE);
        }

        mBtnSubmit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        ObjectAnimator scalexShow =  ObjectAnimator.ofFloat(mBtnSubmit,View.SCALE_X,1f,1.1f);
                        ObjectAnimator scaleYShow =  ObjectAnimator.ofFloat(mBtnSubmit,View.SCALE_Y,1f,1.1f);
                        AnimatorSet setShow = new AnimatorSet();
                        setShow.playTogether(scalexShow,scaleYShow);
                        setShow.setInterpolator(new DecelerateInterpolator());
                        setShow.setDuration(300);
                        setShow.start();
                        break;
//                    case MotionEvent.ACTION_MOVE:
//                        break;
                    case MotionEvent.ACTION_UP:
                        callBackFragmentGct.saveItemQuesAnswer();
                        CNtxlPaperEntity.get(childIndex).getFavouriteAndNote().setSubmitState(2);

                        ObjectAnimator scalexShow1 =  ObjectAnimator.ofFloat(mBtnSubmit,View.SCALE_X,1.1f,1f);
                        ObjectAnimator scaleYShow1 =  ObjectAnimator.ofFloat(mBtnSubmit,View.SCALE_Y,1.1f,1f);
                        AnimatorSet setShow1 = new AnimatorSet();
                        setShow1.playTogether(scalexShow1,scaleYShow1);
                        setShow1.setInterpolator(new DecelerateInterpolator());
                        setShow1.setDuration(300);
                        setShow1.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
//                                mBtnSubmit.setVisibility(View.GONE);
//                                mLlGctAnswer.setVisibility(View.VISIBLE);
                                hideBtnSubmit();
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                        setShow1.start();
                        break;
//                    case MotionEvent.ACTION_CANCEL:
//
//                        ObjectAnimator scalexShow2 =  ObjectAnimator.ofFloat(mBtnSubmit,View.SCALE_X,1.1f,1f);
//                        ObjectAnimator scaleYShow2 =  ObjectAnimator.ofFloat(mBtnSubmit,View.SCALE_Y,1.1f,1f);
//                        AnimatorSet setShow2 = new AnimatorSet();
//                        setShow2.playTogether(scalexShow2,scaleYShow2);
//                        setShow2.setInterpolator(new DecelerateInterpolator());
//                        setShow2.setDuration(300);
//                        setShow2.start();
//                        break;
                }
                return true;
            }
        });

    }

    private void showBtnSubmit(){
        if(mBtnSubmit.getVisibility()==View.GONE) {
            mBtnSubmit.setVisibility(View.VISIBLE);
            ObjectAnimator translationY1 = ObjectAnimator.ofFloat(mBtnSubmit, View.TRANSLATION_Y, 300f, 0f);
            ObjectAnimator translationY2 = ObjectAnimator.ofFloat(mBtnSubmit, View.TRANSLATION_Y, 300f, 0f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY1,translationY2);
            setShow.setDuration(800);
            setShow.start();
        }
    }

    private void hideBtnSubmit(){
        if(mBtnSubmit.getVisibility()==View.VISIBLE) {
            ObjectAnimator translationY1 = ObjectAnimator.ofFloat(mBtnSubmit, View.TRANSLATION_Y, 0f, 300f);
            ObjectAnimator translationY2 = ObjectAnimator.ofFloat(mBtnSubmit, View.TRANSLATION_Y, 0f, 300f);
            AnimatorSet setShow = new AnimatorSet();
            setShow.playTogether(translationY1,translationY2);
            setShow.setDuration(800);
            setShow.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    mBtnSubmit.setVisibility(View.GONE);
                    mLlGctAnswer.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            setShow.start();
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser&& isFristTime){
            isFristTime = false;
            Log.e("==setUserVisibleHint==","===========mLlContainer==========="+mLlContainer);
            final Handler mH = new Handler();
            mH.post(new Runnable() {
                @Override
                public void run() {
                    if(mLlContainer==null){
                        mH.post(this);
                    }else{
                        final int containerWidth = mLlContainer.getMeasuredWidth() - mLlContainer.getPaddingRight()
                                - mLlContainer.getPaddingLeft();
                        final LayoutInflater inflater = getLayoutInflater();

                        /** 用来测量字符的宽度 */
                        final Paint paint = new Paint();
                        final TextView textView = (TextView) inflater.inflate(R.layout.item_textview, null);
                        final int itemPadding = textView.getCompoundPaddingLeft() + textView.getCompoundPaddingRight();
                        final LinearLayout.LayoutParams tvParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        tvParams.setMargins(0, 0, itemMargins, 0);

                        paint.setTextSize(textView.getTextSize());

                        LinearLayout layout = new LinearLayout(getActivity());
                        layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                        layout.setOrientation(LinearLayout.HORIZONTAL);
                        mLlContainer.addView(layout);

                        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        params.setMargins(0, lineMargins, 0, 0);

                        /** 一行剩下的空间 **/
                        int remainWidth = containerWidth;

                        for (int i = 0; i < tags.length; ++i) {
                            final String text = tags[i];
                            final float itemWidth = paint.measureText(text) + itemPadding;
                            if (remainWidth > itemWidth) {
                                addItemView(inflater, layout, tvParams, text);
                            } else {
                                resetTextViewMarginsRight(layout);
                                layout = new LinearLayout(getActivity());
                                layout.setLayoutParams(params);
                                layout.setOrientation(LinearLayout.HORIZONTAL);
                                /** 将前面那一个textview加入新的一行 */
                                addItemView(inflater, layout, tvParams, text);
                                mLlContainer.addView(layout);
                                remainWidth = containerWidth;
                            }
                            remainWidth = (int) (remainWidth - itemWidth + 0.5f) - itemMargins;
                        }
                        resetTextViewMarginsRight(layout);

                        mH.removeCallbacks(this);
                    }
                }
            });

        }
    }

    /***************** 将每行最后一个textview的MarginsRight去掉 *********************************/

    private void resetTextViewMarginsRight(ViewGroup viewGroup) {
        Log.e("AASSAA","==============CCCC==================="+(viewGroup.getChildCount() - 1));
        final TextView tempTextView = (TextView) viewGroup.getChildAt(viewGroup.getChildCount() - 1);
        tempTextView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

    }

    private BubbleDialog.Position mPosition = BubbleDialog.Position.TOP;
    private BubbleDialog mCurrentDialog;
    private void addItemView(LayoutInflater inflater, ViewGroup viewGroup, ViewGroup.LayoutParams params, final String text) {
        final TextView tvItem = (TextView) inflater.inflate(R.layout.item_textview, null);
        tvItem.setText(text);
        tvItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("addItemView","===============点击内容=================="+text);
//                tvItem.setPaintFlags(tvItem.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);//中间横线（删除线）
//                tvItem.setPaintFlags(tvItem.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));//取消 中间横线（删除线）

                int SubmitState = CNtxlPaperEntity.get(childIndex).getFavouriteAndNote().getSubmitState();
                if(SubmitState!=2) {

                    BubbleLayout bl = new BubbleLayout(getActivity());
                    bl.setBubbleColor(Color.BLACK);
                    bl.setShadowColor(Color.GRAY);
                    bl.setLookLength(Util.dpToPx(getActivity(), 6));//10
                    bl.setLookWidth(Util.dpToPx(getActivity(), 8));//10
                    bl.setBubbleRadius(0);

                    ObjectAnimator scalexShow =  ObjectAnimator.ofFloat(bl,View.SCALE_X,0f,1.0f);
                    ObjectAnimator scaleYShow =  ObjectAnimator.ofFloat(bl,View.SCALE_Y,0f,1.0f);
                    AnimatorSet setShow = new AnimatorSet();
                    setShow.playTogether(scalexShow,scaleYShow);
                    setShow.setInterpolator(new DecelerateInterpolator());
                    setShow.setDuration(300);
                    setShow.start();

                    /*
                     * 取消作答
                     * */
//                mCurrentDialog = new BubbleDialog(getActivity())
//                        .addContentView(LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_gct_cancle_answer, null))
//                        .setClickedView(tvItem)
//                        .setPosition(mPosition)
//                        .setBubbleLayout(bl)
//                        .setOffsetY(10)
//                        .calBar(true)
//                        .softShowUp();
//                mCurrentDialog.show();
//                TextView mTvCancle = mCurrentDialog.findViewById(R.id.tv_cancle);
//                mTvCancle.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        tvItem.setPaintFlags(tvItem.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));//取消 中间横线（删除线）

//                        tvItem.getPaint().setFlags(0);
//                        tvItem.invalidate();
//                        mCurrentDialog.dismiss();
//                    }
//                });


                    /*
                     * 开始作答
                     * */
                    mCurrentDialog = new BubbleDialog(getActivity())
                            .addContentView(LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_gct_answer, null))
                            .setClickedView(tvItem)
                            .setPosition(mPosition)
                            .setBubbleLayout(bl)
                            .setOffsetY(-16)//10
                            .calBar(true)
                            .softShowUp();
                    mCurrentDialog.show();

                    final LinearLayout mLlDialogOne = mCurrentDialog.findViewById(R.id.ll_dialogOne);
                    final LinearLayout mLlDialogTwo = mCurrentDialog.findViewById(R.id.ll_dialogTwo);

                    //删除
                    TextView mTvDelect = mCurrentDialog.findViewById(R.id.tv_delect);
                    mTvDelect.setOnClickListener(new View.OnClickListener() {
                        @SuppressLint("ResourceAsColor")
                        @Override
                        public void onClick(View v) {
//                            tvItem.setPaintFlags(tvItem.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);//中间横线（删除线）

                            tvItem.getPaint().setFlags( Paint.STRIKE_THRU_TEXT_FLAG);
                            tvItem.invalidate();
                            mCurrentDialog.dismiss();
                        }
                    });
                    //修改
                    TextView mTvChange = mCurrentDialog.findViewById(R.id.tv_change);
                    mTvChange.setOnClickListener(new View.OnClickListener() {
                        @SuppressLint("ResourceAsColor")
                        @Override
                        public void onClick(View v) {
//                            tvItem.getPaint().setFlags( Paint.STRIKE_THRU_TEXT_FLAG);
//                            tvItem.invalidate();
//                            mCurrentDialog.dismiss();
                            mLlDialogOne.setVisibility(View.GONE);
                            mLlDialogTwo.setVisibility(View.VISIBLE);
                        }
                    });
                    //前增
                    TextView mTvAddFront = mCurrentDialog.findViewById(R.id.tv_add_front);
                    mTvAddFront.setOnClickListener(new View.OnClickListener() {
                        @SuppressLint("ResourceAsColor")
                        @Override
                        public void onClick(View v) {
                            tvItem.getPaint().setFlags( Paint.STRIKE_THRU_TEXT_FLAG);
                            tvItem.invalidate();
                            mCurrentDialog.dismiss();
                        }
                    });
                    //后增
                    TextView mTvAddAfter = mCurrentDialog.findViewById(R.id.tv_add_after);
                    mTvAddAfter.setOnClickListener(new View.OnClickListener() {
                        @SuppressLint("ResourceAsColor")
                        @Override
                        public void onClick(View v) {
                            tvItem.getPaint().setFlags( Paint.STRIKE_THRU_TEXT_FLAG);
                            tvItem.invalidate();
                            mCurrentDialog.dismiss();
                        }
                    });



                }else{
                    LancooUtils.showShort(getActivity(),"已提交，不能再修改");
                }
            }
        });

        viewGroup.addView(tvItem, params);

    }

    /****************************************************************************************************/


    public interface CallBackFragmentGct {
        void pageMoveNext();
        void saveItemQuesAnswer();
    }

}